﻿@page "/System/Menu"
@attribute [TabItemOption(Text = "菜单管理")]
@using System.Diagnostics.CodeAnalysis;
@using BootstrapBlazorApp.Shared.Data.SYS;
@inject MessageService msg


@inject ICacheManager CacheManager

<div>
    <Table TItem="MenuDto" IsTree="true" AutoGenerateColumns="true"
           IsStriped="true" IsBordered="true" IsMultipleSelect="true"
           ShowToolbar="true" ShowExtendButtons="true" ShowLoading="true"
           OnAddAsync="@OnAddAsync" OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync" @bind-SelectedRows="SelectedItems" EditDialogItemsPerRow="2"
           ShowExportButton="true" TreeNodeConverter="@TreeNodeConverter" OnTreeExpand="@OnTreeExpand" OnQueryAsync="@OnQueryAsync">
        <TableColumns>
            <TableColumn CssClass="col-sm-6" @bind-Field="@context.AppCode" Lookup="AppCode" />
            <TableColumn CssClass="col-sm-6" @bind-Field="@context.MenuType"  Lookup="MenuType" />
        </TableColumns>
        <EditTemplate>
            <div class="row g-3 form-inline">
                <div class="col-12 col-sm-6">
                    <Select Items="AppCode" @bind-Value="@context.AppCode" maxlength="50"></Select>
                </div>
                <div class="col-12 col-sm-6">
                    <Select Items="MenuType" @bind-Value="@context.MenuType" maxlength="50"></Select>
                </div>
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.MenuCode"  />
                </div>
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.Name" />
                </div>
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.Icon" />
                </div>
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.Url" />
                </div>
                <div class="col-12 col-sm-6">
                    <BootstrapInput @bind-Value="@context.ParentCode" />
                </div>
            </div>
        </EditTemplate>
    </Table>
</div>

@code {

    /// <summary>
    /// 当前Token信息
    /// </summary>
    [CascadingParameter]
    private ITokenContext? Context { get; set; }

    private IEnumerable<SelectedItem> AppCode { get; set; }

    private IEnumerable<SelectedItem> MenuType { get; set; }

    private List<MenuDto> SelectMenus = new List<MenuDto>();

    private MenuDto CurrentDic { get; set; } = new MenuDto();

    [NotNull]
    private List<MenuDto>? SelectedItems
    {
        get { return SelectMenus; }
        set
        {
            SelectMenus = value;
            if (value.Count > 0)
            {
                CurrentDic.ParentCode = SelectedItems[0].MenuCode;
                CurrentDic.AppCode = SelectedItems[0].AppCode;
            }

        }
    }


    /// <summary>
    /// OnInitialized 方法
    /// </summary>
    protected async override void OnInitialized()
    {
        base.OnInitialized();

        // 模拟数据从数据库中获得
        AppCode = Request.System.QueryDictionaryByTypeAsync("AppCode").Result.data;
        MenuType = Request.System.QueryDictionaryByTypeAsync("MenuType").Result.data;

        var data = await Request.System.QueryMenuAsync();
    }

    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="_"></param>
    /// <returns></returns>
    private async Task<QueryData<MenuDto>> OnQueryAsync(QueryPageOptions _)
    {
        var response = await Request.System.QueryMenuAsync();

        var data = new QueryData<MenuDto>()
            {
                Items = response.data
            };
        return data;
    }

    private Task<IEnumerable<TableTreeNode<MenuDto>>> TreeNodeConverter(IEnumerable<MenuDto> items)
    {
        // 构造树状数据结构
        var ret = BuildTreeNodes(items, null);
        return Task.FromResult(ret);

        IEnumerable<TableTreeNode<MenuDto>> BuildTreeNodes(IEnumerable<MenuDto> items, string? parentCode)
        {
            var ret = new List<TableTreeNode<MenuDto>>();
            var menuDtos = items.Where(i => i.ParentCode == parentCode);
            foreach (var item in menuDtos)
            {
                var temp = new TableTreeNode<MenuDto>(item);
                temp.HasChildren = items.Any(i => i.ParentCode == item.MenuCode);
                //temp.IsExpand = temp.HasChildren;
                temp.Items = BuildTreeNodes(items, item.MenuCode);
                ret.Add(temp);

            }
            //ret.AddRange(items.Where(i => i.ParentCode == parentCode).Select((foo, index) => new TableTreeNode<MenuDto>(foo)
            //    {
            //        //是否有子节点
            //        HasChildren = items.Any(i => i.ParentCode == foo.MenuCode),
            //        // 如果子项集合有值 则默认展开此节点
            //        IsExpand = items.Any(i => i.ParentCode == foo.MenuCode),
            //        // 获得子项集合
            //        Items = BuildTreeNodes(items.Where(i => i.ParentCode == foo.MenuCode), foo.MenuCode)
            //    }));
            return ret;
        }
    }

    private async Task<IEnumerable<TableTreeNode<MenuDto>>> OnTreeExpand(MenuDto foo)
    {
        var ret = new List<TableTreeNode<MenuDto>>();
        return ret;
    }

    private Task<MenuDto> OnAddAsync()
    {
        return Task.FromResult(CurrentDic);
    }

    private async Task<bool> OnSaveAsync(MenuDto item, ItemChangedType changedType)
    {
        if (changedType == ItemChangedType.Add)
        {
            item.Creater = Context.CurrentUser.Account;
            item.CreatedName = Context.CurrentUser.UserName;
            return await Global.ExecuteApiAsync(() => Request.System.AddMenuAsync(item));
        }
        else
        {
            item.Modifier = Context.CurrentUser.UserName;
            item.ModifiedName = Context.CurrentUser.UserName;
            return await Global.ExecuteApiAsync(() => Request.System.UpdateMenuAsync(item));
        }
    }

    private async Task<bool> OnDeleteAsync(IEnumerable<MenuDto> items)
    {
        return await Global.ExecuteApiAsync(() => Request.System.DeleteMutiMenuAsync(items.ToList()));
    }
}
